/**
 * CreditEase.cn Inc.
 * Copyright (c) 2006-2015 All Rights Reserved.
 */
package com.hunlian.makelove.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.text.TextUtils;

/**
 * 签名验证工具类
 * 
 * @author qinghua Wang
 * @version $Id: SignUtil.java, v 0.1 2015年4月23日 下午5:37:41 qhwang Exp $
 */
public class SignUtil {

    public static boolean checkSign(Map<String, String> params, String securityKey) {

        String sign = (String)params.get("sign");

        boolean result = true;
        String genSign = genSign(params, securityKey);
        if (!genSign.equals(sign)) {
            result = false;
        }
        return result;
    }

    public static String genSign(Map<String, String> params, String securityKey) {
    	if (params == null) {
    	    params = new HashMap<String, String>(); //避免空指针
    	}

        List<String> list = new ArrayList<String>(params.keySet());
        Collections.sort(list);
        StringBuffer sbVali = new StringBuffer();
        int size = list.size();
        String key;
        for (int i = 0; i < size; i++) {
            key = list.get(i);
            if (!"sign".equals(key) && !TextUtils.isEmpty((String)params.get(key)) && params.get(key) != null) {
                sbVali.append(key + "=" + String.valueOf(params.get(key)) + "&");
            }
        }
        sbVali.append("key=" + securityKey);
        
        DigestWrapper dw = new DigestWrapperImpl();
        
        return dw.generateMd5(sbVali.toString());
    }

}
